package main

import (
	"fmt"
	"time"
)

func closeChannel() {
	c := make(chan int, 5)
	go func() {
		for i := 0; i < 5; i++ {
			c <- i
		}
		close(c)
	}()

	// for {
	// 	v, ok := <-c
	// 	if !ok {
	// 		fmt.Println("channel closed")
	// 		break
	// 	}
	// 	fmt.Println("v: ", v)
	// }
	for data := range c {
		fmt.Println("v: ", data)
	}
}
func goChannel() {
	// 无缓冲
	// c := make(chan int)
	c := make(chan int, 5)
	// 使用chan交互goroutine
	go func(a, b int) {
		defer fmt.Println("goroutine end")
		fmt.Println("goroutine run")
		c <- a + b
	}(10, 20)

	num := <-c
	fmt.Println(num)

	go func() {
		defer fmt.Println("goroutine end")
		for i := 0; i < 5; i++ {
			c <- i
			fmt.Println("goroutine run: ", i)
		}
	}()
	time.Sleep(2 * time.Second)
	fmt.Println("size: ", len(c), " cap: ", cap(c))
	closeChannel()
}
